package com.comtrade.activities;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.comtrade.device.BeaconApkConfig;
import com.comtrade.ilserver.tasks.ConnectTask;
import com.comtrade.ilserver.tasks.User;
import com.comtrade.sharedpreferences.DomesticSharedPreferences;
import com.example.beaconapk.R;

public class LoginActivity extends Activity{

	private DomesticSharedPreferences sharedPreferences;
	
	
	EditText username;
	EditText password;
	EditText url;
	Button btnLogIn;
	Button btnRegister;
	
	private User korisnik;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login); 

		 sharedPreferences = new DomesticSharedPreferences();				
		 username = (EditText)findViewById(R.id.et_user);
		 password = (EditText)findViewById(R.id.et_pass);
		 url = (EditText)findViewById(R.id.et_url);
		 
		 //--------------popunjava polja ako postoji
		 String user = sharedPreferences.getPreferences(getApplicationContext(), "USERNAME");
		 String pass = sharedPreferences.getPreferences(getApplicationContext(), "PASSWORD");
		 
		 if(user!="" && pass!="")
		 {
			 username.setText(user);
			 password.setText(pass);			 
		 }
		 
		 String url_address = sharedPreferences.getPreferences(getApplicationContext(), "URL");
		 Log.d("IP PROBA",url_address);
		 String IP = sharedPreferences.UzmiSamoIP(url_address);		 
		 url.setText(IP);
		 //------------------------------------------
		 
		 btnLogIn = (Button)findViewById(R.id.btn_logIn);
		 btnRegister = (Button)findViewById(R.id.btn_Register);
		 		 
		 btnRegister.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String urlString = url.getText().toString();
				
				if (urlString.trim().length() > 0 && urlString != null){
					sharedPreferences.savePreferences(getApplicationContext(), "URL", sharedPreferences.OdIPuURL(urlString));
					
					Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
					startActivity(i);
				}
			}
		});
		 
		 
		 btnLogIn.setOnClickListener(new OnClickListener() {
			
			

			@Override
			public void onClick(View v) {

				String userString = username.getText().toString();
				String passString = password.getText().toString();
				String urlString = url.getText().toString();
				
				
				if (userString.trim().length() > 0 && userString != null &&
						passString.trim().length() > 0 && passString != null &&
						urlString.trim().length() > 0 && urlString != null){
					
					//-------------pamti u shared preferences
					sharedPreferences.savePreferences(getApplicationContext(), "URL", sharedPreferences.OdIPuURL(urlString));
					sharedPreferences.savePreferences(getApplicationContext(), "USERNAME", userString);
					
					//ako su uneta sva polja
					
					if(passString.length() > 3){
						//-----------zapamti u shared preferences
						sharedPreferences.savePreferences(getApplicationContext(), "PASSWORD", passString);
						ConnectTask ct = new ConnectTask();
						//Slanje podataka na server						
						ct.setPassword(passString);
						ct.setUsername(userString);
						
						ct.execute(sharedPreferences.OdIPuURL(urlString)+"/rest/signin");
						
						try {
							
							String result = ct.get();	
												
							if(result == null){
								
								Context context = getApplicationContext();
								CharSequence text = "NEUSPESNO!";
								int duration = Toast.LENGTH_LONG;

								Toast toast = Toast.makeText(context, text, duration);
								toast.show();
							}
							else {
								korisnik = User.fromJSON(result);
								ArrayList<String> roles = korisnik.getRole();
								
								if(roles.size()==1)
								{
									String s = roles.get(0).toString();
									String s2 = new String("client");
									if (s.equals(s2)) {
										Intent i = new Intent(LoginActivity.this, GuideActivity.class);
										i.putExtra("USER", korisnik);
										startActivity(i);
									}								
								}else{
									String s = roles.get(0).toString();
									String s1 = roles.get(1).toString();
									String s2 = roles.get(2).toString();
									if(s.equals("client") || s1.equals("admin") || s2.equals("monitoring_officer")){
										Dialog();
									}
									
								}
								
								
								Context context = getApplicationContext();
								CharSequence text = "USPESNO!";
								int duration = Toast.LENGTH_LONG;
								Toast toast = Toast.makeText(context, text, duration);
								toast.show();
								
								//Intent i = new Intent(LoginActivity.this, GuideActivity.class);
								//startActivity(i);
								
							}
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ExecutionException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}else {
						
						//ako password nema 3 karaktera
						Context context = getApplicationContext();
						CharSequence text = "Password must have minimum 4 characters!";
						int duration = Toast.LENGTH_LONG;

						Toast toast = Toast.makeText(context, text, duration);
						toast.show();
					}
				}else {
					//ako nisu uneta sva polja
					
					Context context = getApplicationContext();
					CharSequence text = "All fields must be filled!";
					int duration = Toast.LENGTH_LONG;

					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
				}
			}
		});
	}

	protected void Dialog(){
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				final AlertDialog dialog = builder
						.setTitle("Choose:")
						.setMessage("Proceed as ?")
						.setPositiveButton("Monitoring user",
								new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Intent i = new Intent(LoginActivity.this, NetworksActivity.class);
								/*	User k=(User)getIntent().getExtras().get("USER");
								i.putExtra("USER",k);*/
								startActivity(i);
							}
						})
						.setNegativeButton("Device user",
								new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							Intent i = new Intent(LoginActivity.this, GuideActivity.class);
							/*	User k=(User)getIntent().getExtras().get("USER");
								i.putExtra("USER",k);*/
								startActivity(i);
								//dialog.dismiss();
								//finishActivity(0);
							}
						}).create();
				dialog.show();
	}
		 
		 
	@Override
	protected void onResume() {		
		super.onResume();
		
		String url_address = sharedPreferences.getPreferences(getApplicationContext(), "URL");
		url_address = sharedPreferences.UzmiSamoIP(url_address);	
		url.setText(url_address);
		String user = sharedPreferences.getPreferences(getApplicationContext(), "USERNAME");
		username.setText(user);
		String pass = sharedPreferences.getPreferences(getApplicationContext(), "PASSWORD");
		password.setText(pass);						
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.shared_preferences, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}